package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.base.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1/file/")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //目标 把文件储存到服务器


        //1.获取原始文件名
        String filename = file.getOriginalFilename();
        //2.获取文件名后缀 .jpg
        String suffix=filename.substring(filename.lastIndexOf("."));
        //生成全球唯一的文件名: 14bbd25e-7b7a-42d3-a57f-9e9bfccb7044.jpg
        filename=UUID.randomUUID()+suffix;
        System.out.println(filename);
        //4.处理日期路径
        SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");
        String dataPath = sdf.format(new Date());
        //5.创建对应目录 d:/files/2025/05/27
        String dirPath="d:/files";
        File file1=new File(dirPath+dataPath);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //6.保存文件到服务器
        String filePath=dirPath+dataPath+filename;
        file.transferTo(new File(filePath));
        //7.返回响应
        //前端:通过访问http://localhost:8080/2025/05/27/xxx.jpg在浏览器中显示图片
        return JsonResult.ok(dataPath+filename);
    }
}
